//
//  WJGCDTimer.swift
//  MyTest
//
//  Created by guanzhongwang on 2021/5/27.
//

import Foundation
typealias WJGCDTimerBlock = ()->Void
// GCD实现定时器
class WJGCDTimer {
    static let `default` = WJGCDTimer() // 单例
    private lazy var timers = [String:DispatchSourceTimer]()// 存放定时器的数组
     func scheduledDispatchTimer(withName name:String?,timerInterval:Double,queue:DispatchQueue = .main,repeates:Bool=true,action:@escaping WJGCDTimerBlock){
        guard name != nil else {
            return
        }
        var timer = self.timers[name!]
        if timer == nil {
            timer = DispatchSource.makeTimerSource(flags: [], queue: queue)
            timer?.activate()//激活
            timers[name!] = timer//存入列表
        }
        timer?.schedule(deadline: .now(), repeating: timerInterval, leeway: .milliseconds(100))
        timer?.setEventHandler(handler: {
            [weak self] in
            action()
            if repeates == false{
                // 销毁timer
                self?.destoryTimer(withName: name)
            }
        })
    }
    // 暂停
    func suspend(withName name:String?) {
        guard let timer = timers[name!] else {
            return
        }
        timer.suspend()
    }
    // 重启
    func resume(withName name:String?) {
        guard let timer = timers[name!] else {
            return
        }
        timer.resume()
    }
    // 销毁定时器
    func destoryTimer(withName name:String?)  {
        guard let timer = timers[name!] else {
            return
        }
        timers.removeValue(forKey: name!)
        timer.cancel()
    }
    // 检测定时器是否已存在
    func isExistTimer(withName name:String?) -> Bool {
        guard timers[name!] != nil else {
            return false
        }
        return true
    }
    // 隐藏init方法
    private init() {
        
    }
}

